package com.tongguan.paypos.common;

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.tongguan.paypos.R;
import com.tongguan.paypos.utils.L;
import com.tongguan.paypos.utils.NetUtils;
import com.tongguan.paypos.utils.ToastUtils;
import com.tongguan.paypos.view.CustomProgressDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.request.RequestCall;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;

/**
 * Created by Joylive on 2016/10/12 .
 */

public class RequestCallback {

    private static final String TAG = "flag_log"; //log 一直打开
    private static final String MEDIA_TYPE = "application/json;charset=utf-8";
    private static CustomProgressDialog dialog_ms = null;
    private static ArrayList<RequestCall> sRequestCalls = new ArrayList<>();

    public interface HttpCallback {
        void onResponse(String response, int id);

        void onError(Call call, Exception e, int id);
    }

    //取消网络请求  post2
    public static void cancelAllRequest() {
        for (RequestCall requestCall : sRequestCalls) {
            requestCall.cancel();
        }
    }

    /**
     * post请求 判断网络状态  同时加载Dialog  使用dialog 注意 同一个时段只有一个网络请求时才能开启 ，不然造成 状态不对。一个页面只能有一个dialog
     * <p>
     */

    public static void post(final Context context, String url, @NonNull final Map params, final HttpCallback callback) {
        post(context, url, params, null, callback);
    }

    public static void post(final Context context, String url, @NonNull final Map params, final CustomProgressDialog dialog, final HttpCallback callback) {
        post(context, url, params, dialog, true, callback);
    }

    public static void post(final Context context, String url, @NonNull final Map params, final CustomProgressDialog dialog, boolean isShow, final HttpCallback callback) {
        switch (User.getInstance().getNetConnectType()) {
            case 0:
                url = UrlConstants.BASE_URL + url;
                break;
            case 1:
                url = UrlConstants.BASE_URL1 + url;
                break;
            case 2:
                url = UrlConstants.BASE_URL2 + url;
                break;
            case 3:
                url = UrlConstants.BASE_URL3 + url;
                break;
        }
        String json = new Gson().toJson(params);//对象必须初始化
        if (NetUtils.isConnected(context)) {
            if (dialog != null && isShow) {
                dialog.show();
            }
            L.d_net(TAG, "========request'log=======");
            L.e_net(TAG, "url :" + url);
            L.e_net(TAG, "content :" + json);
            L.d_net(TAG, "========request'log=======end");
            long startTime = System.currentTimeMillis();
            RequestCall call = OkHttpUtils.postString().url(url).content(json).mediaType(MediaType.parse(MEDIA_TYPE)).build();
            call.execute(new StringCallback() {
                @Override
                public void onBefore(Request request, int id) {
                    super.onBefore(request, id);
                    sRequestCalls.add(call);
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    long endTime = System.currentTimeMillis();
                    L.d_net(TAG, "========response'log=======");
                    L.e_net(TAG, "error :" + e.getMessage(), e);
                    L.d_net(TAG, "========response'log=======end");
                    L.i_net(TAG, "request data time :" + (endTime - startTime) + "ms");
                    if (context == null) {
                        return;
                    }
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    if ("Canceled".equals(e.getMessage()) || "Socket closed".equals(e.getMessage())) {
                        return;
                    }
                    if (e instanceof SocketTimeoutException){
                        ToastUtils.showCustom(context, R.string.error_timeout);
                    }else {
                        ToastUtils.showCustom(context, R.string.error_net);
                    }
                    callback.onError(call, e, id);
                }

                @Override
                public void onResponse(String response, int id) {
                    long endTime = System.currentTimeMillis();
                    L.d_net(TAG, "========response'log=======");
                    L.e_net(TAG, "response :" + response);
                    L.d_net(TAG, "========response'log=======end");
                    L.i_net(TAG, "request data time :" + (endTime - startTime) + "ms");
                    if (context == null) {
                        return;
                    }
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    if (TextUtils.isEmpty(response) || TextUtils.equals(response, "{}")) {
                        ToastUtils.showCustomLong(context, "data is null ...");
                        return;
                    }
                    callback.onResponse(response, id);
                }

                @Override
                public void onAfter(int id) {
                    super.onAfter(id);
                    sRequestCalls.remove(call);
                }
            });
        } else {
            ToastUtils.showCustom(context, R.string.common_net_error);
        }
    }


    public static void postUrl(final Context context, String url, @NonNull final Map params, boolean isShow, final HttpCallback callback) {
        String json = new Gson().toJson(params);
        if (NetUtils.isConnected(context)) {
            dialog_ms = new CustomProgressDialog(context, "加载中....");
            if (isShow) {
                dialog_ms.show();
            }
            L.d_net(TAG, "========request'log=======");
            L.e_net(TAG, "url :" + url);
            L.e_net(TAG, "content :" + json);
            L.d_net(TAG, "========request'log=======end");
            long startTime = System.currentTimeMillis();
            RequestCall call = OkHttpUtils.postString().url(url).content(json).mediaType(MediaType.parse(MEDIA_TYPE)).build();
            call.execute(new StringCallback() {
                @Override
                public void onBefore(Request request, int id) {
                    super.onBefore(request, id);
                    sRequestCalls.add(call);
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    long endTime = System.currentTimeMillis();
                    L.d_net(TAG, "========response'log=======");
                    L.e_net(TAG, "error :" + e.getMessage(), e);
                    L.d_net(TAG, "========response'log=======end");
                    L.i_net(TAG, "request data time :" + (endTime - startTime) + "ms");
                    if (dialog_ms != null && dialog_ms.isShowing()) {
                        dialog_ms.dismiss();
                    }
                    if (context == null) {
                        return;
                    }
                    if ("Canceled".equals(e.getMessage()) || "Socket closed".equals(e.getMessage())) {
                        return;
                    }
                    ToastUtils.showCustom(context, R.string.error_net);
                    callback.onError(call, e, id);
                }

                @Override
                public void onResponse(String response, int id) {
                    long endTime = System.currentTimeMillis();
                    L.d_net(TAG, "========response'log=======");
                    L.e_net(TAG, "response :" + response);
                    L.d_net(TAG, "========response'log=======end");
                    L.i_net(TAG, "request data time :" + (endTime - startTime) + "ms");
                    if (dialog_ms != null && dialog_ms.isShowing()) {
                        dialog_ms.dismiss();
                    }
                    if (context == null) {
                        return;
                    }
                    if (TextUtils.isEmpty(response) || TextUtils.equals(response, "{}")) {
                        ToastUtils.showCustom(context, "data is null ...");
                        return;
                    }
                    callback.onResponse(response, id);
                }

                @Override
                public void onAfter(int id) {
                    super.onAfter(id);
                    sRequestCalls.remove(call);
                }
            });
        } else {
            ToastUtils.showCustom(context, R.string.common_net_error);
        }
    }
}
